You can run Node.js application an console based or web-based application. Console based application will run your system terminal and a web-based application will use an inbuilt web server to make an application accessible on the web browser.
Console-based Hello World Example
Use the Node.js console module to print output on your system console. Create a JavaScript file
1 | console.log('Hello World'); |
Execute your script using the node
node nodejs_hello_console.js [output] Hello World!
Web-based Hello World Example
A Node.js web application is build with 3 parts.
- Import module to create web server
- Create a web server
- Read client requests and send reponse back to client
Below is the sample application uses http module. http module creates a web server similar to Apache or Nginx web servers. Now create a server with specified host and port. Use used 0.0.0.0 host address means it will listen on all interfaces attached to the system.
Create a JavaScript file
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const http = require('http'); const host = '0.0.0.0'; const port = 3000; const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello World!'); }); server.listen(port, host, () => { console.log('Web server running at http://%s:%s',host,port ); }); |
Execute the script using node. It will start a web server on specified port and host.
node nodejs_hello_web.js [output] Web server running at http://0.0.0.0:3000
For example, above script started a web server on port 3000. Visit your server on a defined port in the web browser. It will show you the result like below.